<template>
    <el-dialog :model-value="show" :title="id == 0 ? '添加用户' : '编辑用户'" @close="closeDialogFn(false)">
        <el-form :model="form" :rules="rules">
            <el-form-item label="账号" label-width="140px" prop="username">
                <el-input v-model="form.username" autocomplete="off" placeholder="请输入账号" />
            </el-form-item>
            <el-form-item label="姓名" label-width="140px" prop="nickName">
                <el-input v-model="form.nickName" autocomplete="off" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="邮箱" label-width="140px" prop="email">
                <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="密码" label-width="140px" prop="password">
                <el-input v-model="form.password" type="password" autocomplete="off" placeholder="请输入密码" show-password
                    :disabled="id != 0" />
            </el-form-item>
            <el-form-item label="备注" label-width="140px">
                <el-input v-model="form.note" type="textarea" :rows="3" autocomplete="off" placeholder="请输入备注" />
            </el-form-item>
            <el-form-item label="是否启用" label-width="140px">
                <el-radio-group v-model="form.status" class="ml-4">
                    <el-radio :label="1" size="large">是</el-radio>
                    <el-radio :label="0" size="large">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialogFn(false)">取消</el-button>
                <el-button type="primary" @click="submitFn">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup lang='ts'>
import { reactive, toRef, watch } from 'vue'
const emit = defineEmits(['close'])
import { addUserInfoApi, queryEditUserApi, updadateUserInfoApi } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
// const dialogFormVisible = ref(false)
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    id: {
        type: Number,
        default: 0
    }
})
const id = toRef(props, 'id') // 获取id的ref对象，方便后续操作id的值或者是在组件销
watch(id, () => {
    if (id.value === 0) return;
    // 向服务器请求数据回来渲染到表单
    queryEditUserApi(id.value).then(res => { 	// 回来的数据应该是一个对象或数组，根
        if (res.code === 200) {
            // 在表单中渲染
            Object.assign(form, res.data);
        }
    })
})

const initForm = {
    username: '',
    nickName: '',
    email: '',
    password: '',
    note: '',
    status: 1,
    id: 0,
};

const form = reactive<IUserListModel>({ ...initForm })

const validtePassword = (rule: any, value: string, callback: any) => {
    if (!value) {
        return callback(new Error('请输入密码'))
    }
    if (!/\d/.test(value)) {
        return callback(new Error('密码中必须包含数字'))
    }
    if (!/[a-zA-Z]/.test(value)) {
        return callback(new Error('密码中必须包含字母'))
    }
    if (/\W/.test(value)) {
        return callback(new Error('密码中包含非法字符'))
    }
    callback();
}

const rules = {
    username: [
        { required: true, trigger: 'blur', message: '请输入账号' },
        { min: 6, max: 20, trigger: 'blur', message: '账号必须在6~20个字符之间' },
    ],
    nickName: [
        { required: true, trigger: 'blur', message: '请输入姓名' },
    ],
    email: [
        { required: true, trigger: 'blur', message: '请输入邮箱' },
        { trigger: 'blur', message: '请输入正确的邮箱', pattern: /^\w+[@]\w+[.]\w+/ },
    ],
    password: [
        { required: true, trigger: 'blur', message: '请输入密码' },
        { trigger: 'blur', message: '密码必须由数字、字母组成', validator: validtePassword },
    ]
}

const closeDialogFn = (isReload: boolean) => {
    emit('close', isReload)
    // 清空 表单数据
    Object.assign(form, initForm) 	// 把右边对象里面的每个键，合并到左边对象 
    // 上面这行代码相当于下面这部分代码
    // for (let key in initForm) {
    //     form[key] = initForm[key] // 把每个字段的值设置到右边对象中
    // }
    // 因为下面的代码，其实就是上面的循环一行一行写
    // form.username = initForm.username
    // form.nickName = initForm.nickName
}

const addUser = () => {
    // 让用户确认
    ElMessageBox.confirm("确定要添加新用户吗", "确认操作", {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then(() => {
        addUserInfoApi(form).then(res => {
            if (res.code === 200) {
                ElMessage({
                    type: 'success',
                    message: '添加成功'
                })
                // 隐藏弹出的dialog
                // emit('close', true);
                closeDialogFn(true);
            }
        })
    }).catch(() => { })
}

const updateUser = () => {
    ElMessageBox.confirm("确认要修改该用户的信息吗", "确认操作", {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then(() => {
        updadateUserInfoApi(form).then(res => {
            if (res.code === 200) {
                // 提示
                ElMessage({
                    type: 'success',
                    message: '修改成功'
                })
                closeDialogFn(true);
            }
        })
    }).catch(() => { })
}

const submitFn = () => {
    // 在发请求之前要，验证表单是否已经通过 - 这个操作在登录做过了 - 自己根据之前做登录的时候的做法，自己做
    id.value === 0 ? addUser() : updateUser()
}

</script>
<style lang="less" scoped></style>